# -*- coding: utf-8 -*-

import sys,time,math,traceback,os
from datetime import  datetime
from list import *
from form import *
from MyWidget import *
from dataService import DataService
import numpy as np

exePath = os.path.dirname(os.path.realpath(sys.executable))

'''自定义主窗口'''
class MyWindow(QMainWindow, Ui_MainWindow):
    dataService = DataService()
    bg_pic=(exePath+'/img/bg.jpg',exePath+'/img/bg1.jpg',exePath+'/img/bg2.jpg',exePath+'/img/bg3.jpg')
    #bg_pic = ( 'img/bg.jpg',  'img/bg1.jpg',  'img/bg2.jpg',  'img/bg3.jpg')
    bg_pic_index = 0
    curr_page = 0
    page_size = 10
    all_total = 0
    all_pages = 0
    condition_name = ''
    header_list = ['编号', '姓名', '性别', '年龄','就诊时间','身份证号','联系方式','就诊情况','家庭住址','操作']

    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)
        self.setupUi(self)
        self.complementTableView()
        self.loadData()
        self.addForm = None
        self.modifyForm = None


    #TODO 完善页面空间样式、增加监听事件等
    def complementTableView(self):
        #self.setWindowOpacity(0.9)  # 设置窗口透明度
        #self.setAttribute(QtCore.Qt.WA_TranslucentBackground)  # 设置窗口背景透明
        self.setWindowFlag(Qt.MSWindowsFixedSizeDialogHint)
        self.setStyleSheet("#MainWindow{border-image:url("+MyWindow.bg_pic[0]+");}")
        #美化表格
        self.tableView.verticalHeader().hide()  # 隐藏行号
        # self.tableView.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)
        #self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # 水平充满
        self.tableView.horizontalHeader().setStyleSheet("QHeaderView::section{background:#3cb0e7;}")
        self.tableView.horizontalHeader().setFixedHeight(30)
        self.tableView.setSelectionMode(QAbstractItemView.SingleSelection)
        # self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows) #选中一行
        #self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)  # 禁止编辑

        #美化按钮
        #self.btn_search_2.setStyleSheet('''QPushButton{border-radius:5px;}''')

        #按钮监听事件
        self.btn_search_2.clicked.connect(self.queryBtnAction)
        self.btn_reset_2.clicked.connect(self.resetBtnAction)
        self.pushButton_4.clicked.connect(self.prePageAction)
        self.pushButton_6.clicked.connect(self.nextPageAction)
        self.pushButton_5.clicked.connect(self.lastPageAction)
        self.pushButton_3.clicked.connect(self.firstPageAction)
        self.pushButton.clicked.connect(self.addAction)
        self.tableView.clicked.connect(self.tableViewClickAction)


    #加载数据
    def loadData(self,*emit):
        datas = MyWindow.dataService.query_by_page(MyWindow.curr_page,MyWindow.page_size,MyWindow.condition_name)
        self.model = QStandardItemModel(len(datas), len(MyWindow.header_list))
        self.model.setHorizontalHeaderLabels(MyWindow.header_list)
        self.tableView.setModel(self.model)
        self.all_total = MyWindow.dataService.getAllTotal()
        self.all_pages = math.ceil(self.all_total/MyWindow.page_size)
        self.label_total.setText('共 '+str(self.all_total)+' 条记录 | 共 '+str(self.all_pages)+' 页')

        if len(datas) > 0:
            for row in range(len(datas)):
                for col in range(len(MyWindow.header_list) - 1):
                    it = QStandardItem(str(datas[row][col]))
                    it.setToolTip(str(datas[row][col]))
                    self.model.setItem(row, col, it)
                self.tableView.setIndexWidget(self.model.index(row,len(MyWindow.header_list)-1),self.getOperateBtn(datas[row]))


    # 组装列表的操作按钮
    def getOperateBtn(self,selectedRow):
        delBtn = QtWidgets.QPushButton()
        delBtn.setText('删除')
        delBtn.setObjectName('del_' + str(selectedRow[0]))
        delBtn.setFixedWidth(40)
        delBtn.setFixedHeight(20)
        delBtn.setStyleSheet('''QPushButton{background:#6DDF6D;border-radius:5px;}QPushButton:hover{background:green;}''')
        delBtn.clicked.connect(lambda :self.delBtnAction(selectedRow[0]))

        modifyBtn = QtWidgets.QPushButton()
        modifyBtn.setText('修改')
        modifyBtn.setObjectName('modify_' + str(selectedRow[0]))
        modifyBtn.setFixedWidth(40)
        modifyBtn.setFixedHeight(20)
        modifyBtn.setStyleSheet('''QPushButton{background:#6DDF6D;border-radius:5px;}QPushButton:hover{background:green;}''')
        modifyBtn.clicked.connect(lambda :self.modifyBtnAction(selectedRow))

        widget = QtWidgets.QWidget()
        horizontalLayout = QtWidgets.QHBoxLayout(widget)
        horizontalLayout.addWidget(modifyBtn)
        horizontalLayout.addWidget(delBtn)
        return widget


    #查询按钮事件
    def queryBtnAction(self):
        MyWindow.condition_name = self.lineEdit_name.text()
        MyWindow.curr_page = 0
        MyWindow.page_size = 10
        self.loadData()


    #重置事件
    def resetBtnAction(self):
        self.lineEdit_name.setText('')
        MyWindow.condition_name = ''
        self.loadData()


    #上一页
    def prePageAction(self):
        self.lineEdit_name.setText('')
        MyWindow.condition_name = ''
        if MyWindow.curr_page == 0:
            reply = QMessageBox.information(self,'提示','已经是首页',QMessageBox.Yes)
        else:
            MyWindow.curr_page -= 1
            self.label.setText(str(MyWindow.curr_page+1))
            self.loadData()


    #下一页
    def nextPageAction(self):
        self.lineEdit_name.setText('')
        MyWindow.condition_name = ''
        if MyWindow.curr_page >= MyWindow.dataService.getAllTotal()/MyWindow.page_size -1:
            QMessageBox.information(self,'提示','已经是最后一页',QMessageBox.Yes)
        else:
            MyWindow.curr_page += 1
            self.label.setText(str(MyWindow.curr_page+1))
            self.loadData()


    #首页
    def firstPageAction(self):
        self.lineEdit_name.setText('')
        MyWindow.condition_name = ''
        self.label.setText('1')
        MyWindow.curr_page = 0
        self.loadData()


    #尾页
    def lastPageAction(self):
        self.lineEdit_name.setText('')
        MyWindow.condition_name = ''
        lastPage = int(MyWindow.dataService.getAllTotal() / MyWindow.page_size)
        MyWindow.curr_page = lastPage
        self.label.setText(str(MyWindow.curr_page+1))
        self.loadData()


    #删除事件
    def delBtnAction(self,indexNo):
        alertInfo = QMessageBox.warning(self,'提示','确定删除？',QMessageBox.Yes | QMessageBox.No)
        if alertInfo == QMessageBox.Yes:
            MyWindow.dataService.delete_row(indexNo)
            self.loadData()


    # 修改事件
    def modifyBtnAction(self,selectedRow):
        self.modifyForm = MyDialogForm(opt='modify',row = selectedRow)
        self.modifyForm.form_signal.connect(self.loadData)
        self.modifyForm.show()


    # 新增事件
    def addAction(self):
        self.addForm = MyDialogForm(opt='add')
        self.addForm.form_signal.connect(self.loadData)
        self.addForm.show()


    #监听窗口关闭  显示事件
    def showEvent(self, evt):
        print(self.windowTitle(), '窗口显示了')

    def closeEvent(self, *args, **kwargs):
        alertInfo = QMessageBox.warning(self, '提示', '是否要退出程序？', QMessageBox.Yes | QMessageBox.No)
        if alertInfo == QMessageBox.Yes:
            splash = QtWidgets.QSplashScreen(QtGui.QPixmap(exePath+'/img/ddt.gif'))
            splash.show()
            splash.showMessage('程序退出中', QtCore.Qt.AlignCenter, Qt.blue)
            MyWindow.dataService.WB.close()
            MyWindow.dataService.APP.quit()
            time.sleep(3)
            splash.close()

            args[0].accept()
        else:
            args[0].ignore()


    #监听表格点击事件
    def tableViewClickAction(self):
        pass
        # print(self.tableView.currentIndex().row())
        # print(self.tableView.currentIndex().column())
        # print(self.tableView.currentIndex().data())


    #监听按键事件
    def keyPressEvent(self,evt):
        if evt.modifiers()==Qt.ShiftModifier and evt.key() == Qt.Key_C :
            MyWindow.bg_pic_index += 1
            self.setStyleSheet("#MainWindow{border-image:url(" + MyWindow.bg_pic[MyWindow.bg_pic_index % 4] + ");}")



''' 增加和修改弹出框'''
class MyDialogForm(QMainWindow,Ui_DialogForm):
    dataService1 = DataService()

    def __init__(self, opt=None, row=None, parent=None):
        super(MyDialogForm, self).__init__(parent)
        self.setupUi(self)
        self.setWindowFlags(QtCore.Qt.WindowMaximizeButtonHint | QtCore.Qt.WindowMinimizeButtonHint)
        self.opt = opt
        self.row = row
        self.completeRow = None
        self.picZoom = None
        self.picNamesArr = None
        self.fillData()
        self.pushButtonCancel.clicked.connect(self.close)
        self.pushButtonOk.clicked.connect(self.save)
        self.addTab.clicked.connect(self.addPic)
        self.center()


    # 让多窗口之间传递信号 刷新主窗口信息
    form_signal = QtCore.pyqtSignal(str)

    def fillData(self):
        if self.row is not None:
            self.completeRow = self.dataService1.query_by_index(self.row[0]) #重新查一遍完整的记录
            self.lineEditName.setText(self.row[1])
            if self.row[2] == '男':
                self.radioButtonSex.setChecked(True)
            else:
                self.radioButtonSex2.setChecked(True)
            self.spinBoxAge.setValue(int(self.row[3]))
            date_p = datetime.strptime(self.row[4], '%Y-%m-%d %H:%M:%S')
            self.dateTimeEdit.setDateTime(QtCore.QDateTime(QtCore.QDate(date_p.year,date_p.month,date_p.day),
                                                          QtCore.QTime(date_p.hour,date_p.minute,date_p.second)))
            self.lineEditIDCard.setText(self.row[5])
            self.lineEditAddress.setText(self.row[6])
            self.textEditDesc.setText(self.row[7])
            self.lineEditBak.setText(self.row[8])

            #加载图片
            if self.completeRow[9] is not None and self.completeRow[9] != '':
                self.picNamesArr = self.completeRow[9].split(';')
                if len(self.picNamesArr) > 0:
                    gLayout = QHBoxLayout(self.scrollAreaWidgetContents)
                    for i in range(len(self.picNamesArr)):
                        picLabel = MyPicLabel(self.picNamesArr[i])
                        picLabel.doubleClick.connect(self.showBigPic)
                        picLabel.delClick.connect(self.delPic)
                        gLayout.addWidget(picLabel)
                    self.scrollAreaWidgetContents.setLayout(gLayout)
        else:
            if self.opt == 'add':
                date_p = datetime.now()
                self.dateTimeEdit.setDateTime(QtCore.QDateTime(QtCore.QDate(date_p.year, date_p.month, date_p.day),
                                                               QtCore.QTime(date_p.hour, date_p.minute, date_p.second)))

    #保存 TODO 增加些校验
    def save(self):
        try:
            splash = QtWidgets.QSplashScreen(QtGui.QPixmap(exePath+'/img/ddt.gif'))
            splash.show()
            splash.showMessage('保存中...', QtCore.Qt.AlignCenter, Qt.blue)
            #time.sleep(5)

            sex = '男' if self.radioButtonSex.isChecked() else '女'
            jzTime = self.dateTimeEdit.dateTime().toString("yyyy-MM-dd HH:mm:ss")
            if self.picNamesArr is None or len(self.picNamesArr) == 0:
                picNames = ''
            else:
                picNames = ';'.join(self.picNamesArr)
            record = [self.lineEditName.text(),sex,str(self.spinBoxAge.value()),jzTime,self.lineEditIDCard.text(),
                      self.lineEditAddress.text(), self.textEditDesc.toPlainText(),self.lineEditBak.text(),picNames]
            if self.opt == 'add':
                result = self.dataService1.add_row(record)
            else:
                record.insert(0,self.row[0])
                result = self.dataService1.update_row(record)

            if result:
                self.close()
            else:
                reply = QMessageBox.warning(self, "警告", "操作失败，请检查参数！")
            splash.close()
        except Exception as e:
            splash.close()
            print(traceback.format_exc())

    def closeEvent(self, *args, **kwargs):
        self.form_signal.emit(self.opt)


    def addPic(self):
        imgNames, imgTypes = QFileDialog.getOpenFileNames(self, "打开图片", "", "*.jpg;;*.png;;All Files(*)")
        if len(imgNames) > 0:
            #获取布局容器
            gLayout = self.scrollAreaWidgetContents.findChild(QHBoxLayout)
            if gLayout is None:
                gLayout = QHBoxLayout(self.scrollAreaWidgetContents)

            #删除原有图片
            # for childW in self.scrollAreaWidgetContents.findChildren(MyPicLabel):
            #     gLayout.removeWidget(childW)
            #     childW.setParent(None)

            #展示新增选中图片
            for i in range(len(imgNames)):
                picLabel = MyPicLabel(imgNames[i])
                picLabel.doubleClick.connect(self.showBigPic)
                picLabel.delClick.connect(self.delPic)
                gLayout.addWidget(picLabel)
            self.scrollAreaWidgetContents.setLayout(gLayout)

            #保存新增图片路径
            if self.picNamesArr is None:
                self.picNamesArr = np.array(imgNames,ndmin=1)
            else:
                self.picNamesArr.extend(imgNames)
        else:
            QMessageBox.warning(self, "提示", "未选中图片！")


    #双击图片展示大图
    def showBigPic(self,*emit):
        if len(emit) > 0:
            imgName = emit[0]
            print(imgName)
            try:
                self.picZoom = MyPictureZoom(imgName)
                self.picZoom.show()
            except Exception as e:
                print(traceback.format_exc())

    #删除照片
    def delPic(self,*emit):
        if len(emit) > 0:
            imgName = emit[0]
            self.picNamesArr.remove(imgName)
            gLayout = self.scrollAreaWidgetContents.findChild(QHBoxLayout)
            for childW in self.scrollAreaWidgetContents.findChildren(MyPicLabel):
                if imgName==childW.imgName:
                    gLayout.removeWidget(childW)
                    childW.setParent(None)


    def showEvent(self, *args, **kwargs):
        pass

    #屏幕中央显示
    def center(self):
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2,(screen.height() - size.height()) / 2)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    myWin = MyWindow()
    myWin.show()
    sys.exit(app.exec_())
